package com.mali.malibackendgateway.filters;


import com.mali.backendcommon.properties.JwtProperties;
import com.mali.backendcommon.util.JwtUtil;
import com.mali.malibackendgateway.config.AuthProperties;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class loginFilter implements GlobalFilter , Ordered {
    private  final AuthProperties authProperties;
    private final JwtProperties jwtProperties;
    private final String USER_ID="user_id";

    private AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request
        ServerHttpRequest request = exchange.getRequest();
        //2.判断是否需要进行拦截
        if(isExclude(request.getPath().toString()))
        {
            return chain.filter(exchange);
        }
        //3.获取token
        String token=null;
        List<String> headers =request.getHeaders().get("authorization");
        if(headers!=null&& !headers.isEmpty())
        {
            token=headers.get(0);
        }
        // 4.校验并解析token
        Long userId;
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
             userId= Long.valueOf(claims.get(USER_ID).toString());
        } catch (Exception e) {
            // 如果无效，拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }

        //5.传递用户id
        System.out.println("userid= "+userId);
        String userInfo=userId.toString();
        ServerWebExchange swe = exchange.mutate().request(builder -> builder.header("user_info", userInfo)).build();
        //6.放行
        return chain.filter(swe);
    }

    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(excludePath,path))
                return true;
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
